<script setup lang='ts'>
import { useRoute } from 'vue-router'
import { reactive, onMounted, onBeforeMount, onUnmounted, nextTick, effect } from 'vue'
import {MenuView} from '@/store/nav'
import nav from '@/store/nav'
import emitter from '@/util/mitt'

const route = useRoute()
const useMav = nav.setup().store

const state: {
      componentKey: string
      keepAliveComponentNameList: string[]
  } = reactive({
    componentKey: route.name as string,
    keepAliveComponentNameList: []
  })

effect(() => {
  if (useMav.navTabSelete) state.componentKey = route.name as string
  if (useMav.navTabOpenArr) state.keepAliveComponentNameList = useMav.navTabOpenArr
})

const addKeepAliveComponentName =  (keepAliveName: string | null) => {
  if (keepAliveName) {
    const index = state.keepAliveComponentNameList.indexOf(keepAliveName)
    if (index !== -1) return
    state.keepAliveComponentNameList.push(keepAliveName)
  }
}

const onTabViewRefresh = (menu:MenuView) => {
  state.keepAliveComponentNameList = state.keepAliveComponentNameList.filter((code: string) => menu.code !== code)
  state.componentKey = ''
  nextTick(() => {
    state.componentKey = route.name as string
    addKeepAliveComponentName(menu.code)
  })
}

onBeforeMount(() => {
  emitter.on('viewRefresh', onTabViewRefresh)
})

onUnmounted(() => {
  emitter.off('viewRefresh')
})

onMounted(() => {
  addKeepAliveComponentName(useMav.navTabSelete)
})

</script>

<template>
  <el-main class="home-main">
    <el-scrollbar :always="true" class="home-main-scrollbar" wrap-class="d-common-post-abs d-common-full">
      <router-view v-slot="{ Component}">
        <keep-alive :include="state.keepAliveComponentNameList">
          <component :is="Component" v-if="state.componentKey" :key="state.componentKey" />
        </keep-alive>
      </router-view>
    </el-scrollbar>
  </el-main>
</template>

<style scoped lang="less">
.home-main {
  padding: 0 !important;
  overflow: hidden;
  width: 100%;
  flex: 1;
}
.home-main-scrollbar {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}
</style>